package com.flyoil.petromp.ui.activity.activity_matter;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cnpc.fyutils.ToastUtils;
import com.cnpc.fyviewlibrary.view.ListScrollview;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.adapter.adapter_order.ItemOrderMessageGoodsAdapter;
import com.flyoil.petromp.adapter.adapter_order.ItemOrderMessageSignatureAdapter;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseActivity;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.entity.entity_order.MapListEntity;
import com.flyoil.petromp.mvp_p.MessagePresenter.OrderMessagePresenter;
import com.flyoil.petromp.mvp_v.MessageUIView.OrderMessageUIView;
import com.flyoil.petromp.utils.Dialog.DialogApproveUtil;
import com.flyoil.petromp.utils.Dialog.Dialog_util;
import com.flyoil.petromp.utils.OrderUtl.OrderListUtil;
import com.flyoil.petromp.utils.OrderUtl.OrderMessageUtil;
import com.flyoil.petromp.view.SignatureTopView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单据的详情界面
 */
public class OrderMessageActivity extends BaseActivity implements OrderMessageUIView {
    private ListScrollview list_signature;
    private ItemOrderMessageSignatureAdapter adapter_signature;
    private LinearLayout line_basic;
    private OrderMessageUtil orderMessageUtil;
    private ScrollView scrollView;
    private TextView tv_signature, tv_signature_botton;
    private SignatureTopView signatureTopView;
    private RelativeLayout rela_layout;
    private int scrollviewYHeight = 0;//滑动的距离
    private OrderMessagePresenter presenter;
    private String order_type = "";
    private View line_signature;
    private ImageView img_remove_icon;
    private int OrderConfirmId;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_order_message;
    }

    @Override
    protected void initViews() {
        super.initViews();
        order_type = getIntent().getStringExtra("order_type");
        if (order_type == null) {
            order_type = "";
        }
        orderMessageUtil = new OrderMessageUtil(mContext,order_type);
        httpModel = new HttpModel();
        setBackOnclickListner(mContext);
        list_signature = $(R.id.list_matter_message_signature);
        scrollView = $(R.id.scro_matter_message);
        tv_signature = $(R.id.tv_matter_message_signature);
        line_signature = $(R.id.line_order_message_signature_fgx);
        img_remove_icon = $(R.id.img_order_message_stastus_remove_icon);
        tv_signature_botton = $(R.id.tv_matter_message_signature_botton);
        list_signature.setDividerHeight(0);
        adapter_signature = new ItemOrderMessageSignatureAdapter(mContext);
        list_signature.setAdapter(adapter_signature);
        line_basic = $(R.id.line_matter_message_basic);
        signatureTopView = $(R.id.signa_matter_message);
        rela_layout = $(R.id.rele_matter_message_layout);
        presenter = new OrderMessagePresenter(this, order_type);
        setTextTitleName(orderMessageUtil.getOrderMessageTitle(order_type));
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        scrollView.setOnScrollChangeListener(onScrollChangeListener);
        tv_signature_botton.setOnClickListener(onClickListener);
        signatureTopView.setAgreeOnclockListener(onClickListener);
        signatureTopView.setUnAgreeOnclockListener(onClickListener);
    }

    @Override
    protected void initdatas() {
        super.initdatas();
        Map<String, Object> map = new HashMap<>();
        map.put("id", getIntent().getIntExtra("id", 0));
        presenter.initNetworkData(map);
    }

    /**
     * 窗口有焦点的时候，即所有的布局绘制完毕的时候，我们来获取布局的高度和myScrollView距离父类布局的顶部位置
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {

        }
    }

    /**
     * scrollview的滑动状态变化监听事件
     */
    private View.OnScrollChangeListener onScrollChangeListener = new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            scrollviewYHeight = scrollY;
            setOnScrollStatus();
        }
    };

    /**
     * 根据滑动的距离修改浮动按钮的状态
     */
    private void setOnScrollStatus() {
        int scrollVisibilityHright = rela_layout.getHeight() + scrollviewYHeight;//获取屏幕底部距离scrollview顶部的距离
        if (scrollVisibilityHright >= tv_signature.getTop() + tv_signature.getHeight()) {//浮动部分已经显示出来了
            tv_signature_botton.setVisibility(View.GONE);
        } else {
            tv_signature_botton.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 控件的点击事件
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_matter_message_signature_botton://底部浮动按钮——签字意见
                    int heightY = tv_signature.getTop() - scrollviewYHeight;
                    scrollView.scrollTo(0, heightY);
                    tv_signature_botton.setVisibility(View.GONE);
                    break;
                case R.id.tv_view_message_signature_agree://批准按钮
                    setOrderApproval("");
                    break;
                case R.id.tv_view_message_signature_unagree://退回按钮
                case R.id.line_view_message_signature_edt://底部输入框的点击事件
                    show_approve_remark_dialog();
                    break;
            }
        }
    };

    /**
     * 显示批准输入框的弹框
     */
    private void show_approve_remark_dialog() {
        final DialogApproveUtil dialogApproveUtil = new DialogApproveUtil(mContext);
        dialogApproveUtil.show_approve_dialog(signatureTopView, 30);
        dialogApproveUtil.setApproveOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogApproveUtil.dismissPopupWindow();
                setOrderApproval(dialogApproveUtil.getEdtMessage());
            }
        });
        dialogApproveUtil.setUnApproveOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialogApproveUtil.getEdtMessage().length() == 0) {
                    ToastUtils.show_toast("请填写签字意见");
                } else {
                    dialogApproveUtil.dismissPopupWindow();
                    setOrderReject(dialogApproveUtil.getEdtMessage());
                }

            }
        });

    }

    @Override
    public void updataToUI(List data) {
        if (data == null) {
            onDataError(null);
        }
        if (data != null && data.size() == 0) {
            onDataNull(null);
        }
    }

    @Override
    public void upDataTextsView(List data) {
        if (data != null && data.size() > 0) {
            onDataSucceed();
        }
        orderMessageUtil.init_text_map_view(data, line_basic);
    }

    @Override
    public void upDataImgsView(String name, List data) {
        if (data != null && data.size() > 0) {
            onDataSucceed();
        }
        orderMessageUtil.init_imgs_view(name, data, line_basic);
    }

    @Override
    public void upDataGoodsView(List data) {
        if (data != null && data.size() > 0) {
            onDataSucceed();
        }
        orderMessageUtil.init_order_message_goods_view(data, line_basic);
    }

    @Override
    public void upDataServiceView(List data) {
        if (data != null && data.size() > 0) {
            onDataSucceed();
        }
        orderMessageUtil.init_order_message_goods_view(data, line_basic);
    }

    @Override
    public void upDataSiganturesView(List data) {
        if (data != null && data.size() > 0) {
            onDataSucceed();
        }
        if (data == null || data.size() == 0) {
            tv_signature.setVisibility(View.GONE);
            tv_signature_botton.setVisibility(View.GONE);
            line_signature.setVisibility(View.GONE);
        } else {
            tv_signature.setVisibility(View.VISIBLE);
            line_signature.setVisibility(View.VISIBLE);
            adapter_signature.addDataBottom(data);
        }
    }

    @Override
    public void upDataRemarkView(MapListEntity entity) {
        orderMessageUtil.init_remark_view(entity, line_basic);
    }

    @Override
    public void upDataShowSigantureView(boolean show) {
        if (show)
            signatureTopView.setVisibility(View.VISIBLE);
        else
            signatureTopView.setVisibility(View.GONE);
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setOnScrollStatus();
            }
        }, 200);
    }

    @Override
    public void upDataTitleName(int imgRese, String name) {
        orderMessageUtil.init_message_title_layout_view(imgRese, name, line_basic);
    }

    @Override
    public void upDataMoneyView(MapListEntity entity) {
        List<MapListEntity> data = new ArrayList<>();
        data.add(entity);
        orderMessageUtil.init_text_map_view(data, line_basic);
    }

    @Override
    public void upDataShowRemoveImagView(boolean show) {
        if (show) {
            img_remove_icon.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) img_remove_icon.getLayoutParams();
            int top = getWindowManager().getDefaultDisplay().getHeight() / 3 - img_remove_icon.getHeight() - 30;
            layoutParams.setMargins(0, top, 0, 0);
            img_remove_icon.setLayoutParams(layoutParams);
        } else {
            img_remove_icon.setVisibility(View.GONE);
        }
    }

    @Override
    public void upDataOrderConfirmId(int id) {
        this.OrderConfirmId = id;
    }

    @Override
    public void upDataShowBackoutView(boolean showck) {
        if (showck) {
            setTextRightName("撤销");
            setTextRightOnclickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setOrderCancel("");
                }
            });
        } else {
            setTextRightName("");
        }
    }

    /**
     * @param opinion 对单据执行批准的操作
     */
    private void setOrderApproval(@NonNull String opinion) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", OrderConfirmId);
        map.put("opinion", opinion);
        Dialog_util.start_NetworkRequests_diolog(mContext);
        httpModel.setOrderApproval(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                Dialog_util.close_NetworkRequests_diolog();
                ToastUtils.show_toast(model.getMessage());
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    setResult(RESULT_OK);
                    line_basic.removeAllViews();
                    initdatas();
                }
            }

            @Override
            public void onFailure(String msg) {
                Dialog_util.close_NetworkRequests_diolog();
            }
        });
    }

    /**
     * @param opinion 对单据进行撤销的操作
     */
    private void setOrderCancel(@NonNull String opinion) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", OrderConfirmId);
        map.put("opinion", opinion);
        Dialog_util.start_NetworkRequests_diolog(mContext);
        httpModel.setOrderCancel(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                Dialog_util.close_NetworkRequests_diolog();
                ToastUtils.show_toast(model.getMessage());
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    setResult(RESULT_OK);
                    line_basic.removeAllViews();
                    initdatas();
                }
            }

            @Override
            public void onFailure(String msg) {
                Dialog_util.close_NetworkRequests_diolog();
            }
        });
    }

    /**
     * @param opinion 对单据执行退回的操作
     */
    private void setOrderReject(@NonNull String opinion) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", OrderConfirmId);
        map.put("opinion", opinion);
        Dialog_util.start_NetworkRequests_diolog(mContext);
        httpModel.setOrderReject(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                Dialog_util.close_NetworkRequests_diolog();
                ToastUtils.show_toast(model.getMessage());
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    setResult(RESULT_OK);
                    line_basic.removeAllViews();
                    initdatas();
                }
            }

            @Override
            public void onFailure(String msg) {
                Dialog_util.close_NetworkRequests_diolog();
            }
        });
    }
}
